<template>
  <n-upload
    multiple
    directory-dnd
    :action="BASE+'/upload'"
    name="avatar"
    @finish="handleFinish"
    @remove="handleRemove"
    :max="1"
  >
    <n-upload-dragger>
      <img v-if="preview" :src="BASE+preview" style="height:100px">
      <div v-else>
        <div style="margin-bottom: 12px">
          <n-icon size="48" :depth="3">
            <AddOutline />
          </n-icon>
        </div>
        <n-text style="font-size: 16px">
          点击或者拖动文件到该区域来上传
        </n-text>
      </div>
    </n-upload-dragger>
  </n-upload>
</template>

<script setup>

import { AddOutline } from '@vicons/ionicons5';
import { useMessage } from 'naive-ui';
import { ref } from 'vue';
import { BASE } from '../config';
const message = useMessage()
const emit = defineEmits(['update:modelValue'])  //此处的emit,等同于选项式中的this.$emit
const preview = ref('') //预览图数据
const handleFinish = (options)=>{
  // console.log('上传成功',options.event.target.response);
  let res = JSON.parse(options.event.target.response)
  // console.log(res);
  let {code,msg,path} = res
  let msgState = ['error','success']
  message[msgState[code]](msg)
  preview.value = path  //预览
  emit('update:modelValue',path)  //将服务器下发的图片链接传给当前组件的调用者的v-model
}
const handleRemove = ()=>{
  preview.value = ''  //预览
  emit('update:modelValue','')
}

//调用组件的时候，接收默认预览图
const props = defineProps(['modelValue'])
preview.value = props.modelValue

</script>

<style lang="scss" scoped>

</style>